package studyguide.ch09.customitem;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.CustomItem;
import javax.microedition.lcdui.Graphics;

public class CustomItemD extends CustomItem {

	private static final int MIN_COMPONENT_WIDTH = 70;
	private static final int MIN_COMPONENT_HEIGHT = 20;
	
	private static final String [] textLines = {
		"Line one.",
		"Line two.",
		"Line three.",
		"Line four.",}; 
	private int currentLine = 0;
	private boolean hasFocus = false;
	
	protected CustomItemD(String label) {
		super(label);

		// Check if device supports traversing
		int iModes = getInteractionModes();
		if ((TRAVERSE_HORIZONTAL | iModes) == 0) {
			throw new RuntimeException("Traversing not supported");
		}
		if ((TRAVERSE_VERTICAL | iModes) == 0) {
			throw new RuntimeException("Traversing not supported");
		}
	}

	protected int getMinContentHeight() {
		return MIN_COMPONENT_HEIGHT;
	}

	protected int getMinContentWidth() {
		return MIN_COMPONENT_WIDTH;
	}

	protected int getPrefContentWidth(int height) {
		return MIN_COMPONENT_WIDTH;
	}

	protected int getPrefContentHeight(int width) {
		return MIN_COMPONENT_HEIGHT;
	}
	
	protected void paint(Graphics g, int w, int h) {
		// Clear screen:
		g.setColor(0x00ffffff);// White
		g.fillRect(0, 0, w, h);
		
		// Draw a border
		g.setColor(0);// Black
		g.drawRect(0, 0, w-1, h-1);
		
		// Draw the message
		g.drawString(textLines[currentLine], 1, 1, Graphics.TOP|Graphics.LEFT);
	}

	protected boolean traverse(
			int dir, 
			int viewportWidth, int viewportHeight,
			int[] visRect_inout) {
		boolean moreLines = false;

		if (!hasFocus) {
			// Focus has entered component. Nothing to update
			hasFocus = true;
			moreLines = true;
		} else {
			// Component already had focus. Perform scroll
			if (dir == Canvas.DOWN || dir == Canvas.RIGHT) {
				// Going down
				if (currentLine + 1 < textLines.length) {
					// End not reached yet
					currentLine ++;
					notifyStateChanged();
					moreLines = true;
				}
			}
			if (dir == Canvas.UP || dir == Canvas.LEFT) {
				// Going up
				if (currentLine > 0) {
					// Start not reached yet
					currentLine --;
					notifyStateChanged();
					moreLines = true;
				}
			}
		}
		
		repaint();
		return moreLines;
	}

	protected void traverseOut() {
		hasFocus = false;
	}

	public int getCurrentLine() {
		return currentLine;
	}

}
